package com.example.imtoken.modules.main.wallet.assets.add

import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.ClickUtils
import com.example.imtoken.R
import com.example.imtoken.core.App
import com.example.imtoken.core.base.BaseActivity
import com.example.imtoken.core.utils.BusConfig
import com.example.imtoken.core.utils.InjectorUtils
import com.example.imtoken.databinding.ActivityAddAssetsBinding
import com.example.imtoken.modules.main.wallet.manage.home.HomeWalletManageActivity
import com.example.imtoken.modules.main.wallet.search.SearchWalletActivity

/**
 * 添加资产
 */
class AddAssetsActivity :
    BaseActivity<AddAssetsViewModel, ActivityAddAssetsBinding>(AddAssetsViewModel::class.java) {

    private lateinit var adapter: AddAssetsAdapter

    override fun initLayoutId(): Int {
        return R.layout.activity_add_assets
    }

    private val viewModelF by lazy {
        getViewModelFactory(InjectorUtils.getAddAssetsViewModel())
    }

    override fun init() {
        BusUtils.register(this)
        initAdapter()
        initClick()
        initHeadView()
        initObserve()

        viewModelF.getCoins(App.createLiveData.value?.coin?.coin)
    }

    @BusUtils.Bus(tag = BusConfig.update_wallet_address_sticky_add_assets_activity, sticky = true)
    fun updateWalletAddress(walletType:String) {
        viewModelF.updateStatus(walletType)
    }

    private fun initClick() {
        ClickUtils.applyGlobalDebouncing(dataBinding.llHomeWalletManage) {
            ActivityUtils.startActivity(HomeWalletManageActivity::class.java)
        }
    }

    private fun initHeadView() {
        dataBinding.activity = this
        dataBinding.headView.ivHeadBack.setOnClickListener { this.finish() }
        ClickUtils.applyGlobalDebouncing(dataBinding.headView.tvSearch) {
            ActivityUtils.startActivity(SearchWalletActivity::class.java)
        }
    }

    private fun initObserve() {
        viewModelF.getDataLiveData().observe(this) {
            adapter.setDiffNewData(it)
        }
    }

    private fun initAdapter() {
        adapter = AddAssetsAdapter(R.layout.item_popular_assets)
        adapter.setDiffCallback(AddAssetsDiffCallback())
        dataBinding.rvPopularAssets.layoutManager = object : LinearLayoutManager(this) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        dataBinding.rvPopularAssets.adapter = adapter
        adapter.setOnItemClickListener { _, _, position ->
            if (!adapter.data[position].isSelect)
                viewModelF.updateStatus(position)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        BusUtils.removeSticky(BusConfig.update_wallet_address_sticky_add_assets_activity)
        BusUtils.unregister(this)
    }

}